<template>
    <el-select
        :key="componentKeys"
        v-model="selectVal"
        :disabled="disabled"
        :clearable="config.clearable"
        :popper-append-to-body="config.popperAppendToBody"
        :popper-class="config.popperClass"
        :size="config.size"
        :collapse-tags="showCollapseTags"
        :placeholder="$t(config.placeholder)"
        :filterable="config.filterable"
        :multiple="config.multiple"
        :allowCreate="config.allowCreate"
        style="width: 100%"
        @clear="
            () => {
                selectChange();
            }
        "
        @blur="selectBlur"
        @change="selectChange($event)"
        @visible-change="visibleChange"
    >
        <template>
            <div v-show="canRefresh" class="refresh">
                <el-button circle @click="selectRefresh(item.refreshKey, item.refreshAPI)">
                    <svg-icon name="refresh" />
                    <span>{{ $t('commonWord.refreshOption') }}</span>
                </el-button>
            </div>
        </template>
        <el-option v-for="(el, index) in item.options" :key="index" :label="$t(el.lang) || el.label" :disabled="el.disabled" :value="el.value" />
        <!-- <span>{{ $t(item.lang) || el.label }}</span> -->
        <!-- <div slot="empty">
      <slot name="empty"><p class="empty">无数据</p></slot>
    </div> -->
    </el-select>
</template>

<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
import { Prop, Watch } from 'vue-property-decorator';
import { ListInterface, Dictionary, Partial, ElBaseConfig, Options } from '@/typings';
import { WatchMounted } from '@/utils/decorator';
// interface SelectConfig extends ElBaseConfig {
//   isUpdate: boolean
// }
const DEFAULT_CONFIG: ElBaseConfig = {
    clearable: true,
    collapseTags: true,
    showItemNumber: 3, // 0代表显示 collapseTags
    filterable: true,
    size: 'mini',
    multiple: false,
    allowCreate: false,
    popperAppendToBody: true
    // placeholder: 'form.placeholder.select'
};
const APPOINT_KEY = ['businessTypeId'];

@Component({
    name: 'base-select'
})

/**
 * @param value = 传入值
 * @param selectProps = 基础属性
 * @param item = 元数据
 * @method change = 值改变时触发
 * */
export default class baseSelect extends Vue {
    @Prop({ default: false }) disabled: boolean;
    @Prop() selectProps: Partial<ElBaseConfig>;
    @Prop() value: string | string[] | number | number[];
    @Prop({ required: true }) item: ListInterface;
    @Prop({ default: '' }) documentStatus; // 单据状态
    selectKey: string = Date.now().toString(36);
    selectVal: string | string[] | number | number[] = '';
    config: ElBaseConfig = DEFAULT_CONFIG;
    @Watch('selectProps', { immediate: true, deep: true })
    onSelectPropsChanged(val: Dictionary<any>) {
        this.config = Object.assign({}, DEFAULT_CONFIG, val);
    }
    @Watch('value', { immediate: true })
    onValueChanged(val) {
        // this.selectVal = val
        // this.selectVal = typeof val === 'string' ? val.split('_')[0] : Number(val.toString.split('_')[0])
        // 这里是 数据的回显 加了时间戳让数据更新
        if (val.toString().includes('_')) {
            this.selectVal = Number(val.toString().split('_')[0]);
            this.$emit('update:value', this.selectVal);
        } else {
            this.selectVal = val;
        }
    }
    @WatchMounted('documentStatus', { immediate: true })
    checkDocumentStatus() {
        // 检测单据状态 [延迟是主要是等reset函数处理完成后再执行这里确定value值是干净的]
        setTimeout(() => {
            // 这里处理 指定字段 当选项只有一个的时候 默认显示
            const options = this.item.options;
            if (options && options.length === 1 && APPOINT_KEY.includes(this.item.value)) {
                const isMultiple = this.config.multiple;
                const options = this.item.options;
                const selectValue = isMultiple ? [options[0]['value']] : options[0]['value'];
                this.selectChange(selectValue);
            }
        }, 500);
    }
    get showCollapseTags() {
        if (!Array.isArray(this.selectVal)) {
            return true;
        } else {
            return this.selectVal.length >= this.config.showItemNumber!;
        }
    }
    get componentKeys() {
        return (this.item.refreshKey || '') + this.selectKey + this.item.options?.length;
    }
    get canRefresh(): boolean {
        return (
            // eslint-disable-next-line no-prototype-builtins
            this.item.hasOwnProperty('refreshKey') &&
            this.item.refreshKey !== '' &&
            // eslint-disable-next-line no-prototype-builtins
            this.item.hasOwnProperty('refreshAPI') &&
            this.item.refreshAPI !== ''
        );
    }
    clear() {
        // this.$emit('update:value', undefined)
        this.$emit('selectChange', undefined);
    }
    selectChange(value) {
        let current: any = null;
        if (!Array.isArray(value)) {
            current = this.item.options!.find((item) => item.value === value);
        }
        // 这里不让值双向绑定 为了应对 选择值还需确认的 场景
        if (!this.config.noUpdated) {
            this.$emit('update:value', value);
        }
        this.$emit('selectChange', value, current);
    }

    visibleChange(flag) {
        this.$emit('visibleChange', flag);
    }
    selectBlur(event) {
        this.$emit('selectBlur', event);
    }
    async selectRefresh(key, api) {
        const res = await this._post({
            url: api,
            data: {
                data: key
            }
        });
        const options: Options[] = res.data.map((item) => {
            return {
                label: item.name,
                value: item.id
            };
        });
        this.$nextTick(() => {
            this.selectKey = Date.now().toString(36);
            this.$set(this.item, 'options', options);
        });
    }
}
</script>

<style lang="scss" scoped>
.empty {
    padding: 10px 0;
    margin: 0;
    text-align: center;
    color: #999;
    font-size: 12px;
}
.refresh {
    position: relative;
    height: 35px;
    padding: 0 10px 0 10px;
    .el-button {
        // float: right;
        border: none;
        span {
            margin-left: 4px;
            color: #186cff;
        }
        &:focus,
        &:hover {
            background: transparent !important;
        }
    }
    svg {
        color: #4689ff;
    }
}
</style>
